package com.wuba.rxjavademo.lyz;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import rx.Observable;

/**
 * Created by liyaxing on 2016/4/12.
 */
public class Demo03 {

    public static void main(String[] ss){
        Demo03 demo = new Demo03() ;
        Observable<List<Long>> observable = demo.bufferObserver() ;
        observable.subscribe(buffer -> {
            System.out.println("buffer : " + buffer);
        }) ;

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private Observable<List<Long>> bufferObserver(){
        return Observable.interval(1, TimeUnit.SECONDS).buffer(2,TimeUnit.SECONDS) ;
    }

    private Observable<Long> timerObserver(){
        return Observable.timer(2,TimeUnit.SECONDS) ;
    }

    private Observable<Integer> repeatObservable(){
        return Observable.just(1).repeat(10) ;
    }

    private Observable<Long> intervalObservable(){

        return Observable.interval(1, TimeUnit.SECONDS) ;
    }

    private Observable<Integer> fromListObserable(){
        List<Integer> list = new ArrayList<>() ;
        list.add(23) ;
        list.add(22) ;
        list.add(3323) ;
        list.add(2443);
        return Observable.from(list) ;
    }

    private Observable<Integer> fromArrayObserable(){
        Integer[] array = {1,23,4,56,67,2} ;
        return Observable.from(array) ;
    }

    private Observable<Integer> createObservable(){
        return Observable.<Integer>create(subscriber -> {
            if (!subscriber.isUnsubscribed()) {
                int count = 0;
                for (int i = 0; i < 5; i++) {
                    int num = new Random().nextInt(10);
                    if (num > 8) {
                        subscriber.onError(new Throwable("num > 8"));
                        break;
                    } else {
                        count++;
                        subscriber.onNext(num);
                    }
                }
                if (count >= 5) {
                    subscriber.onCompleted();
                }
            }
        });
    }

    private Observable<Integer> rangeObservable(){
        return Observable.range(7, 10) ;
    }

    private Observable<Long> justObservable(){
        return Observable.just(System.currentTimeMillis()) ;
    }

    private Observable<Long> deferObservable(){
        return Observable.defer(() -> justObservable()) ;
    }



}
